package org.aurora.remote.netty;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;

@ChannelHandler.Sharable
public class NettyConnectChangeHandler extends ChannelDuplexHandler {
    private NettyEventPublisher nettyEventPublisher;

    public NettyConnectChangeHandler(NettyEventPublisher nettyEventPublisher) {
        this.nettyEventPublisher = nettyEventPublisher;
    }

    /**
     * 当Channel处于活动状态（已连接到远程节点）时被调用。这通常发生在TCP连接建立之后，表示Channel现在可以进行数据传输。
     * 通常发生在TCP连接建立之后
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        this.nettyEventPublisher.publishEvent(new NettyEvent(NettyEventType.CONNECT, ctx.channel()));
    }

    /**
     * 当Channel离开活动状态并且不再连接远程节点时被调用。这通常发生在TCP连接关闭之后，表示Channel现在不再能够进行数据传输。
     * 通常发生在TCP连接关闭之后
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);

        this.nettyEventPublisher.publishEvent(new NettyEvent(NettyEventType.DISCONNECT, ctx.channel()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        this.nettyEventPublisher.publishEvent(new NettyEvent(NettyEventType.EXCEPTION, ctx.channel()));
        // todo 异常，关闭 channel
    }
}
